/************************************************************************/
// Copyright (C) 2016, han_gangbiao. All rights reserved.
// Use of this source code is governed by a GPL-v2 license that can be found in the License file.
// 
// [Time]:      2016-1-4 21:53:17
// [Author]:    han_gangbiao [http://my.oschina.net/jackhen]
// [Info]:      
/************************************************************************/

#ifndef INCLUDE_BASE_XSINGLETON_H_
#define INCLUDE_BASE_XSINGLETON_H_

#include "xmutex.h"

BEG_NS_SMART

template <class T>
class singleton_t
{
public:
    static T* instance()
    {
        if(0 == s_instance_)
        {
            mtx_.lock();
            if(0 == s_instance_)
            {
                s_instance_ = new T;
            }
            mtx_.unlock();
        }
        return s_instance_;
    }
    static void uninstance()
    {
        if(0 != s_instance_)
        {
            mtx_.lock();
            if(0 != s_instance_)
            {
                delete s_instance_;
                s_instance_ = 0;
            }
            mtx_.unlock();
        }
    }

protected:
    singleton_t(){}
    ~singleton_t(){}

private:
    static T*       s_instance_;
    static mutex_t  mtx_;

private:    //emphasize the following members are private
	singleton_t( const singleton_t& );
	const singleton_t& operator=( const singleton_t& );
};

template <class T>
T* singleton_t<T>::s_instance_ = 0;

template <class T>
mutex_t singleton_t<T>::mtx_;

END_NS_SMART

#endif //~INCLUDE_BASE_XSINGLETON_H_
